
import 'package:flutter/services.dart';

class BatteryChannel {
  static const _batteryChannelName = "cn.blogss/battery";
  static late MethodChannel _batteryChannel;

  static void initChannels(){
    _batteryChannel = MethodChannel(_batteryChannelName);
  }

  // 3. 异步任务，通过平台通道与特定平台进行通信，获取电量，这里的平台是 Android
  static getBatteryLevel() async {
    String batteryLevel;
    try {
      final int result = await _batteryChannel.invokeMethod('getBatteryLevel');
      batteryLevel = 'Battery level at $result % .';
    } on PlatformException catch (e) {
      batteryLevel = "Failed to get battery level: '${e.message}'.";
    }

    return batteryLevel;
  }

  static String getBatteryLevelWithThen() {
    String batteryLevel = "Before task.";
    try {
      _batteryChannel.invokeMethod('getBatteryLevel').then((batteryLevel){
        batteryLevel = 'Battery level at $batteryLevel % .';
        return batteryLevel;
      });
    } on PlatformException catch (e) {
      batteryLevel = "Failed to get battery level: '${e.message}'.";
    }
    return batteryLevel;
  }
}